package com.cheyun.netsalev3.view.drivelist

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.MyPagedListAdapter
import com.cheyun.netsalev3.bean.drive.DriveListInfo
import com.cheyun.netsalev3.databinding.DriveListFragmentBinding
import com.cheyun.netsalev3.utils.BaseFragment
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.utils.api.NetworkState
import com.cheyun.netsalev3.viewmodel.DriveListViewModel
import com.jeremyliao.liveeventbus.LiveEventBus

class DriveListFragment : BaseFragment<DriveListFragmentBinding>() {
    private var state = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            state = it.getString("state").toInt()
        }
    }

    override fun initContentView(): Int {
        return R.layout.drive_list_fragment
    }

    override fun initViewModel(): ViewModel? {
        val factory = InjectorUtils.getDriveListViewModelFactory(state)
        return ViewModelProviders.of(this, factory).get(DriveListViewModel::class.java)
    }

    private lateinit var adapter: MyPagedListAdapter<DriveListInfo>

    override fun initView() {
        adapter = MyPagedListAdapter(R.layout.drive_list_item, binding.viewModel)
        var recyclerView = binding.root.findViewById<RecyclerView>(R.id.swipe_target)
        recyclerView.adapter = adapter
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.viewModel?.refresh()
        }

        LiveEventBus.get()
                .with("drivelistupdate", String::class.java)
                .observe(this, Observer {
                    binding.viewModel?.refresh()
                })
    }

    override fun initData() {
        binding.viewModel?.items?.observe(this, Observer { list ->
            list?.apply {
                adapter.submitList(list)
            }
        })
        binding.viewModel?.networkState?.observe(this, Observer {
            binding.swipeRefreshLayout.isRefreshing = it == NetworkState.LOADING
            adapter.setNetworkState(it)
        })
    }

    override fun lazyInit() {
        Log.i(TAG,"override lazyinit")
    }

    companion object {
        @JvmStatic
        fun newInstance(state: String) =
                DriveListFragment().apply {
                    arguments = Bundle().apply {
                        putString("state", state)
                    }
                }
    }


}
